﻿#include <stdio.h>
#include "wrap.h"

using namespace TTFramework;

int mainwin = -1;
void Logger( char16_t* log);
void OnInit();
void OnUpdate();
void OnWinRender(int winid);
void OnExit();

void OnMouseMotion(int winid, int x, int y, bool press);
void OnMouseButton(int winid, int x, int y, uint8_t buttonid, bool press, uint8_t click);


int main(int argc, char** argv)

{
	// TTFramework::LoadNativeCore("native.core.dll");
	TTFramework::LoadDLL();

	//===start app


	APP_SetLogger( Logger );
	// app_mainloop(u"hello window", OnInit, OnUpdate, OnWinRender, OnExit);
	App_MainLoop(u"hello window", OnInit, OnUpdate, OnWinRender, OnExit);
	return 0;
}


void Logger(char16_t* log)
{
	printf("log,%ls.\n", log);

}
int win2nd, win3rd;
Material* mat;
Mesh* mesh;
Material* mat2;
Mesh* mesh2;
Material* mat3;
Mesh* mesh3;
Texture* tex;
void OnInit()
{
	mainwin = Window_GetMainWinID();
	win2nd = Window_Create(u"2ndwin", true);
	win3rd = Window_Create(u"win3rd", true);
	Window_SetPos(win2nd, -1, -1, 400, 300);
	Window_SetPos(win3rd, 100, 100, 400, 300);
	mat = Material_CreateDefault();
	mesh = Mesh_CreateSample();
	mat2 = Material_CreateDefaultTexture();
	mesh2 = Mesh_CreateSample();
	mat3 = Material_CreateDefaultOutline();
	mesh3 = Mesh_CreateSample();
	char data[16];
	for (int i = 0; i < 16; i++)
		data[i] = 0xff;
	tex = Texture_Create(2, 2);
	XYWH xywh;
	xywh.x = 0;
	xywh.y = 0;
	xywh.w =2;
	xywh.h = 2;
	Texture_Upload(tex, xywh, data, 16);
	char16_t buf[256];
	Material_GetUniformName(mat2, 0, buf, 256);

	Events_RegMouse(OnMouseMotion, OnMouseButton, nullptr);
}

void OnWinRender(int winid)
{
	if (winid == mainwin)
	{
		Frame_Clear(0x00aabbff, true, true);
		Matrix_Test();
		Frame_Draw(mat, mesh);
		
		Frame_Draw(mat3, mesh3);

	}
	else
	{
		Frame_Clear(0xccdd00ff, true, true);
		Matrix_Test();
		Material_SetTexture(mat2, 0, tex);
		//Frame_Draw(mat2, mesh2);
		Frame_Draw(mat3, mesh3);

	}

}
void OnExit()
{

}

bool mousedown;
int dragwin = -1;
int dragx;
int dragy;


void OnUpdate()
{
	//resize window
	if (dragwin > 0)
	{
		int mx, my;
		int bts = GetMousePos(&mx, &my);
		if (bts == 0)
		{
			//鼠标已松开
			dragwin = -1;
		}
		else
		{
			int x = mx - dragx;
			int y = my - dragy;
			Window_SetPos(dragwin, x, y, -1, -1);
		}
	}
	else
	{
		int winid = GetFocusWindowID();
		if (winid >= 0 && winid != mainwin)
		{
			int mx, my;

			int bts = GetMousePos(&mx, &my);
			if (bts > 0)
			{
				int x, y, w, h;
				Window_GetPos(winid, x, y, w, h);
				dragx = mx - x;
				dragy = my - y;
				dragwin = winid;

			}
		}
	}
}

void OnMouseMotion(int winid, int x, int y, bool press)
{

}
void OnMouseButton(int winid, int x, int y, uint8_t buttonid, bool press, uint8_t click)
{
	//这种事件只能捕获活动窗口内的，如果要move &resize 他不好使
	// 不跨窗口的内部ui事件可以走这里
	//if (dragwin < 0 && mainwin != winid && press)
	//{
	//	dragwin = winid;
	//	int mx, my;
	//	GetMousePos(mx, my);
	//	int x, y, w, h;
	//	Window_GetPos(winid, x, y, w, h);
	//	dragx = mx - x;
	//	dragy = my - y;
	//	return;
	//}
}